package com.ls.lspicturebackend.manger.websocket;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ls.lspicturebackend.model.entity.Picture;
import com.ls.lspicturebackend.model.entity.Space;
import com.ls.lspicturebackend.model.entity.SpaceUser;
import com.ls.lspicturebackend.model.entity.User;
import com.ls.lspicturebackend.model.enums.SpaceRoleEnum;
import com.ls.lspicturebackend.model.enums.SpaceTypeEnum;
import com.ls.lspicturebackend.service.PictureService;
import com.ls.lspicturebackend.service.SpaceService;
import com.ls.lspicturebackend.service.SpaceUserService;
import com.ls.lspicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserService spaceUserService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            String pictureId = httpServletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)) {
                log.error("缺少图片参数，拒绝建立连接");
                return false;
            }
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (ObjectUtil.isNull(loginUser)) {
                log.error("用户未登录，拒绝建立连接");
                return false;
            }
            // 判断用户是否有该图片的编辑权限
            Picture picture = pictureService.getById(pictureId);
            if (ObjectUtil.isNull(picture)) {
                log.error("图片不存在，拒绝建立连接");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space;
            if (ObjectUtil.isNotNull(spaceId)) {
                space = spaceService.getById(spaceId);
                if (ObjectUtil.isNull(space)) {
                    log.error("图片所在空间不存在，拒绝建立连接");
                    return false;
                }
                if (SpaceTypeEnum.TEAM.getValue() != space.getSpaceType()) {
                    log.error("图片所在空间不是团队空间，拒绝建立连接");
                    return false;
                }
                String userRole = spaceUserService.lambdaQuery()
                        .select(SpaceUser::getSpaceRole)
                        .eq(SpaceUser::getUserId, loginUser.getId())
                        .eq(SpaceUser::getSpaceId, spaceId)
                        .oneOpt()
                        .map(SpaceUser::getSpaceRole)
                        .orElse(null);
                if (Objects.equals(SpaceRoleEnum.getEnumByValue(userRole), SpaceRoleEnum.VIEWER)) {
                    log.error("用户没有该图片的编辑权限，拒绝建立连接");
                    return false;
                }
            }
            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
            attributes.put("pictureId", Long.valueOf(pictureId));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
